import router from "@/router";
// @ts-ignore
import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css';
import {useUserStore} from "@/store/user";
import {useConfigStore} from "@/store/config";

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async (to, from, next) => {
    NProgress.start();
    //判断用户是否已经登录
    const userStore = useUserStore();
    const configStore = useConfigStore();
    const hasLoggedIn = userStore.token;
    if (hasLoggedIn) {
        if (to.path === '/login') {
            next({ path: '/' })
            NProgress.done();
        } else if (to.path === '/user') {
            next();
        } else {
            const hasGetUserInfo = userStore.userInfo.userId;
            if (hasGetUserInfo) {
                console.log('has');
                next()
            } else {
                try {
                    //获取用户信息
                    let result = await userStore.getUserInfo();
                    configStore.setHowUserDialog(!result);
                    result ? next() : next({path: '/user'});
                } catch (error) {
                    console.error(error);
                    next({path: '/login'});
                    NProgress.done();
                }
            }
        }
    } else {
        /* has no token */
        let whiteList = ['/login', '/register', '/404'];
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next()
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next('/login')
            NProgress.done()
        }
    }
})

router.afterEach(() => {
    // 关闭进度条
    NProgress.done()
})
